package com.atguigu.tingshu.payment.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@SuppressWarnings({"all"})
@Slf4j
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private PaymentInfoMapper paymentInfoMapper;
    @Autowired
    private OrderFeignClient orderFeignClient;
    @Autowired
    private AccountFeignClient accountFeignClient;

    /**
     * 保存本地交易记录
     *
     * @param paymentType:支付类型 1301-订单 1302-充值
     * @param orderNo:         订单编号
     * @return
     */
    @Override
    public PaymentInfo savePaymentInfo(String paymentType, String orderNo) {
        //根据订单编号查询该支付信息
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderNo, orderNo));
        //如果存在则直接返回
        if(paymentInfo != null){
            return paymentInfo;
        }
        //如果不存在则手动封装
        paymentInfo = new PaymentInfo();
        //获取用户id
        Long userId = AuthContextHolder.getUserId();
        //用户id
        paymentInfo.setUserId(userId);
        //支付类型：1301-订单 1302-充值
        paymentInfo.setPaymentType(paymentType);
        //订单号
        paymentInfo.setOrderNo(orderNo);
        //付款方式：1101-微信 1102-支付宝
        paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        //支付状态：1401-未支付 1402-已支付
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);

        //如果交易类型为订单
        if(SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)){
            //远程调用 根据订单流水号获取订单信息
            OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderNo).getData();
            Assert.notNull(orderInfo,"订单流水号为:{}的订单不存在",orderNo);
            //判断订单支付状态  未支付才能支付 订单状态：0901-未支付 0902-已支付 0903-已取消
            if(!SystemConstant.ORDER_STATUS_UNPAID.equals(orderInfo.getOrderStatus())){
                throw new GuiguException(500,"订单状态有误: " + orderInfo.getOrderStatus());
            }
            //支付金额
            paymentInfo.setAmount(orderInfo.getOrderAmount());
            //交易内容
            paymentInfo.setContent(orderInfo.getOrderTitle());
        }
        //如果交易类型为充值
        if(SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)){
            //远程调用充值服务 获取到充值信息
            RechargeInfo rechargeInfo = accountFeignClient.getRechargeInfo(orderNo).getData();
            Assert.notNull(rechargeInfo,"订单流水号为:{}的充值记录不存在",orderNo);
            //判断充值状态  充值状态：0901-未支付 0902-已支付 0903-已取消
            if(!SystemConstant.ORDER_STATUS_UNPAID.equals(rechargeInfo.getRechargeStatus())){
                throw new GuiguException(500, "充值状态有误:" + rechargeInfo.getRechargeStatus());
            }
            //支付金额
            paymentInfo.setAmount(rechargeInfo.getRechargeAmount());
            //交易内容
            paymentInfo.setContent("充值: " + rechargeInfo.getRechargeAmount());
        }

        //保存本地记录
        paymentInfoMapper.insert(paymentInfo);
        return paymentInfo;
    }

    /**
     * 支付成功后，更新交易记录
     * @param transaction 微信交易对象
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void updatePaymentInfo(Transaction transaction) {
        //获取订单流水号
        String orderNo = transaction.getOutTradeNo();
        //根据流水号查询支付记录信息
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(
                new LambdaQueryWrapper<PaymentInfo>()
                        .eq(PaymentInfo::getOrderNo, orderNo)
        );
        if(paymentInfo == null){
            log.error("在PaymentInfo表中没有查询到流水号为:{}的数据",orderNo);
            throw new GuiguException(500, "在PaymentInfo表中没有查询到流水号为:" + orderNo + "的数据");
        }
        //如果订单支付状态为未支付
        if(paymentInfo.getPaymentStatus().equals(SystemConstant.PAYMENT_STATUS_UNPAID)){
            //修改支付状态为已支付
            paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
            paymentInfo.setCallbackContent(transaction.toString());
            paymentInfo.setCallbackTime(new Date());
            paymentInfo.setOutTradeNo(transaction.getTransactionId());
            paymentInfoMapper.updateById(paymentInfo);

            //处理支付类型:  支付类型：1301-订单 1302-充值
            //如果是订单
            if(SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentInfo.getPaymentType())){
                //付款成功后 调用远程方法 处理订单相关业务(修改订单支付状态、虚拟发货)
                Result result = orderFeignClient.orderPaySuccess(orderNo);
//                throw new GuiguException(600,"订单付款手动抛出异常测试分布式事务是否生效");
                if(result.getCode().intValue() != 200){
                    throw new GuiguException(500, result.getMessage());
                }
            }

            //如果是充值
            if(SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentInfo.getPaymentType())){
                //付款成功后 远程调用账户服务 修改充值状态 完成充值业务
                Result result = accountFeignClient.rechargePaySuccess(orderNo);
//                throw new GuiguException(600,"充值手动抛出异常测试分布式事务是否生效");
                if(result.getCode().intValue() != 200){
                    throw new GuiguException(500, result.getMessage());
                }
            }
        }

    }
}
